package com.ideaaedi.commonds.zip;

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * zip工具类
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2100.10.12.LTS17
 */
@UtilityClass
public class ZipUtil {

    /**
     * 将多个byte[]数据压缩为ZIP包
     *
     * @param outputStream ZIP包的目标输出流（如文件流或HttpServletResponse输出流）
     * @param files        key-zip中的文件名相对路径（如：file1.txt、aa/bb/cc/user.json）；value-对应byte[]数据
     */
    @SneakyThrows
    public static void compressBytesToZip(OutputStream outputStream, Map<String, byte[]> files) {
        try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
            for (Map.Entry<String, byte[]> entry : files.entrySet()) {
                String fileName = entry.getKey();
                byte[] fileData = entry.getValue();

                // 创建ZipEntry并设置文件名
                ZipEntry zipEntry = new ZipEntry(fileName);
                zos.putNextEntry(zipEntry);

                // 将byte[]写入压缩流
                try (ByteArrayInputStream bis = new ByteArrayInputStream(fileData)) {
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = bis.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                }
                zos.closeEntry();
            }
            zos.finish();
        }
    }

    ///@SneakyThrows
    ///public static void main(String[] args) {
    ///    Map<String, byte[]> files = new HashMap<>();
    ///    files.put("file1.txt", "Hello World".getBytes());
    ///    files.put("aa/bb/cc/user.json", "{\"name\": \"zhang san\"}".getBytes());
    ///    files.put("image.png", IOUtil.toBytes(new File("C:\\Users\\Administrator\\Desktop\\1.png")));
    ///
    ///    try (FileOutputStream fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\output.zip")) {
    ///        compressBytesToZip(fos, files);
    ///    }
    ///}
}
